package game;

import gui.*;

import java.util.*;

import network.GameFinder;

public class GameManager {
	private int playerNum;
	private GameState gameState;
	private GameManagerChanged changeListener;
	private ArrayList<String> ips;
	public GameManager(GameState waitingGame,ArrayList<String> ips,int pNum) {
		gameState = waitingGame;
		this.ips = ips;
		playerNum = pNum;
	}
	public int addPlayer(String ip, String playerName) {
		ips.add(ip);
		gameState.addPlayer(playerName);
		return ips.size()-1;
		
	}
	public void startGame(){
		gameState.dealCards();
		for (int j = 1; j < ips.size(); j++){
			String ip = ips.get(j);
			String otherIps = "";
			for (int i = 0; i < ips.size(); i++){
				if (i != j){
					otherIps += ips.get(i)+",";
				}
			}
			GameFinder.sendMessage(ip, "pk_game_start:"+otherIps);
			GameFinder.sendMessage(ip, "pk_game_state:"+gameState.toString());
		}
		ips.remove(0);
	}
	public void addIp(String ip) {
		ips.add(ip);
	}
	public void updateGameState(String gameState) {
		this.gameState = new GameState(gameState);
		if (changeListener != null){
			changeListener.gameManagerChanged();
		}
		
	}
	public boolean myTurn(){
		return gameState.currentTurn() == playerNum&&gameState.getPhase() != GameState.Phase.WINNER;
	}
	public void fold(){
		if (myTurn()){
			gameState.takeTurn(playerNum, TurnAction.FOLD, 0);
			pushChanges();
		}
	}
	public void checkOrCall(){
		if (myTurn()){
			gameState.takeTurn(playerNum, TurnAction.CHECKORCALL, 0);
			pushChanges();
		}
	}
	public void raise(int amount){
		if (myTurn()){
			gameState.takeTurn(playerNum, TurnAction.RAISE, amount);
			pushChanges();
		}
	}
	public void pushChanges(){
		if (gameState.getPhase() == GameState.Phase.WINNER){
			gameState.payCashToWinner();
			Timer  timer = new Timer();
	        timer.schedule(new TimerTask(){

				@Override
				public void run() {
					gameState.nextHand();
					pushChanges();
					
				}
	        	
	        }, 3*1000);
		}
		for (int j = 0; j < ips.size(); j++){
			System.out.println("IPReceiver:"+ips.get(j));
			String ip = ips.get(j);
			GameFinder.sendMessage(ip, "pk_game_state:"+gameState.toString());
		}
		changeListener.gameManagerChanged();
	}
	public String gameString() {
		return gameState.toString();
	}
	public void setChangeListener(GameManagerChanged g) {
		changeListener = g;
		
	}

}
